package cn.jslancer.webx.dispatcher;

import cn.jslancer.webx.annotation.Application;
import cn.jslancer.webx.config.RequestConfig;
import cn.jslancer.webx.exception.WebxException;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jslancer
 * @date 2018/7/30 23:12
 */
public class RequestMapping {

    private Map<String, RequestConfig> handleMap = new ConcurrentHashMap<>();

    private Map<String, Object> context = new ConcurrentHashMap<>();

    public void register(Object app) {
        Class<?> cls = app.getClass();
        if (cls.isAnnotationPresent(Application.class)) {
            throw new WebxException("Annotation Application not exists");
        }

        Application application = cls.getAnnotation(Application.class);
        String[] path = application.path();
        for (String s : path) {
            componentScan(s);
        }
    }

    public void componentScan(String baseFile) {
        String s = RequestMapping.class.getResource("/" + baseFile).getFile().toString();
        File packageFile = new File(s);
        findFile(packageFile, baseFile);
    }

    /**
     * 递归的方式查找所有file
     *
     * @param file
     */
    public void findFile(File file, String basePackage) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                findFile(f, basePackage);
            }
        } else if (file.isFile()) {
            String fileName = file.getAbsolutePath();
            //将路径转换为包
            String temp = fileName.replaceAll("\\\\", ".");
            //获取正确包路径
            temp = temp.substring(temp.indexOf(basePackage));
            //得到全限定class名
            String className = temp.replaceAll(".class", "");

            // TODO: 2018/7/30 实例化 对象
        }
    }
}
